public class Test13 {
    static class BlockingQueue {
        private int[] tmp = new int[100];
        int head = 0;
        int cur = 0;
        int size = 0;
        private Object object = new Object();

        //生产者
        private void put(int item) throws InterruptedException {
            synchronized (object) {
                //如果队列满了,则进入等待状态
                while (size == tmp.length) {
                    object.wait();
                }
                tmp[cur] = item;
                cur++;
                size++;
                if (cur == tmp.length) {
                    cur = 0;
                }
                object.notify();
            }
        }

        //消费者
        public int consumer() throws InterruptedException {
            //如果为空队列,则进入等待
            synchronized (object) {
                while (size == 0) {
                    object.wait();
                }
                int item = tmp[head];
                head++;
                size--;
                if (head == tmp.length) {
                    head = 0;
                }
                object.notify();
                return item;
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        BlockingQueue blockingQueue = new BlockingQueue();
        Thread put = new Thread(){
            @Override
            public void run() {
                for (int i = 0; i < 1000; i++) {
                    try {
                        blockingQueue.put(i);
                        System.out.println("生产了: " + i);
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        Thread consumer = new Thread(){
            @Override
            public void run() {
                while (true){
                    try {
                        int item = blockingQueue.consumer();
                        System.out.println("消费了: " + item);
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        put.start();
        consumer.start();
        put.join();
        consumer.join();
    }
}